<?php
// This class handles emails
// Email settings can be changed here

require_once("phpmailer/class.phpmailer.php");

class Email
{
	private $host = "www.rtpgrx.com"; // this mainly affect image links, change when host server changes
	private $error = "";
	private $setting = array(); // smtp settings
	public static $BUYER_OPEN=0;
	public static $BUYER_CLOSE=1;
	public static $SUPPLIER_CLOSE=2;
	
	/**
	 * Constructor for Email class
	 */
	public function Email() {		
		$resultset = SystemSet::model()->getSMTPSetting();
		
		// Gets settings from db model
		foreach ($resultset as $record) {
    		$this->setting[$record['name']] = $record['value'];
		}
	}
	
	/**
	 * Description: This method sets the phpmailer parameters and uses the object to send email
	 * Returns: True if email has been sent; False otherwise
	 */
	public function sendEmail($to, $from_name, $subject, $templateID, $data = array()) {
		$mail = new PHPMailer(); 
		$mail->IsSMTP(); // send via SMTP
		$mail->SMTPDebug = 0;
		$mail->SMTPAuth = true; // turn on SMTP authentication
		$mail->SMTPSecure = 'ssl';
		$mail->Host = $this->setting['email_host'];
		$mail->Port = $this->setting['email_port'];
		$mail->Username = $this->setting['email_user_name']; // SMTP username
		$mail->Password = $this->setting['email_password']; // SMTP password
		$mail->SetFrom($this->setting['email_user_name'], $from_name); // (FROM, FROM_NAME)
		$mail->AddAddress($to); //name as optional 2nd arg
		//$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
		//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment
		$mail->IsHTML(true); // send as HTML
		$mail->Subject = $subject;
		
		$mail->Body = $this->getTemplate($templateID, $data); //HTML Body
		
		if(!$mail->Send()) {
			$error = "Mailer Error: " . $mail->ErrorInfo;
			return false;
		}
		else {
			$error = "Message has been sent";
			return true;
		}
	}
	
	/**
	 * Description: This method determines what email template to use depending on the templateID and 
	 * makes a call to other functions to update the template email values
	 * Returns: Email source code as string
	 */
	public function getTemplate($templateID, $data) {
		$template_path;
		
	    if ($templateID == self::$BUYER_OPEN) {
	        $template_path = "templates/buyer-open-order.html";
	        $htmlFile = file_get_contents($template_path, 1);
	        $htmlFile = $this->getBuyerOpenEmail($htmlFile, $data);
	    }
	    else if ($templateID == self::$BUYER_CLOSE) {
	        $template_path = "templates/buyer-close-order.html";
	        $htmlFile = file_get_contents($template_path, 1);
	        $htmlFile = $this->getBuyerCloseEmail($htmlFile, $data);
	        
	    }
	    else if ($templateID == self::$SUPPLIER_CLOSE) {
	        $template_path = "templates/supplier-close-order.html";
	        $htmlFile = file_get_contents($template_path, 1);
	        $htmlFile = $this->getSupplierCloseEmail($htmlFile, $data);
		}
		
		$htmlFile = str_replace('[linkUrl]', Yii::app()->request->getServerName().Yii::app()->request->baseUrl, $htmlFile);
		
		return str_replace('[baseUrl]', $this->host.'/'.str_replace('yii/','',Yii::app()->request->baseUrl), $htmlFile);
	}
	
	/*
	 * Description: This method replaces placeholders for the BUYER OPEN template with appropriate values
	 * Returns: The email source code as string
	 * Note: BUYER OPEN template corresponds to a buyer placing an order. This email is intended for the supplier.
	 */
	public function getBuyerOpenEmail($htmlFile, $data) {
		$resultset = Auctions::model()->getAuction($data['auction_ID']);
		
		foreach ($resultset as $row) {
			$data['auction_start'] = $row->auction_start;
			$data['auction_end'] = $row->auction_end;
			$data['delivery_due'] = $row->delivery_due;
			$data['gallon'] = $row->gallon;
			$productID = $row->product_ID;
			$siteID = $row->site_ID;
			$tankID = $row->tank_ID;
		}
		
		$data['product'] = Products::model()->getProductName($productID);
		$data['site'] = Sites::model()->getSiteName($siteID);
		$data['tank'] = Tanks::model()->getTankName($tankID);
		
		$resultset = Organizations::model()->getOrganization(Yii::app()->user->userID);
		
		foreach ($resultset as $row) {
			$data['organization_name'] = $row->organization_name;
			$data['phone_number'] = $row->phone_number;
			$data['email_address'] = $row->email_address;
			$data['address'] = $row->address1 . ', ' . $row->address2;
			$data['contact_name'] = $row->contact_first_name . ' ' . $row->contact_last_name;
		}
		
		$htmlFile = str_replace('[auctionID]', $data['auction_ID'], $htmlFile);
		$htmlFile = str_replace('[buyer]', $data['organization_name'], $htmlFile);
		$htmlFile = str_replace('[site]', $data['site'], $htmlFile);
		$htmlFile = str_replace('[tank]', $data['tank'], $htmlFile);
		$htmlFile = str_replace('[auctionStart]', $data['auction_start'], $htmlFile);
		$htmlFile = str_replace('[auctionEnd]', $data['auction_end'], $htmlFile);
		$htmlFile = str_replace('[deliveryRequest]', $data['delivery_due'], $htmlFile);
		$htmlFile = str_replace('[product]', $data['product'], $htmlFile);
		$htmlFile = str_replace('[amountRequested]', $data['gallon'], $htmlFile);
		$htmlFile = str_replace('[contact]', $data['contact_name'], $htmlFile);
		$htmlFile = str_replace('[phone]', $data['phone_number'], $htmlFile);
		$htmlFile = str_replace('[email]', $data['email_address'], $htmlFile);
		$htmlFile = str_replace('[address]', $data['address'], $htmlFile);
		
		return $htmlFile;
	}
	
	/*
	 * Description: This method replaces placeholders for the BUYER CLOSE template with appropriate values
	 * Returns: The email source code as string
	 * Note: BUYER CLOSE template corresponds to a buyer closing an order. This email is intended for the supplier.
	 */
	public function getBuyerCloseEmail($htmlFile, $data) {
		return $htmlFile;
	}
	
	/*
	 * Description: This method replaces placeholders for the SUPPLIER OPEN template with appropriate values
	 * Returns: The email source code as string
	 * Note: SUPPLIER OPEN template corresponds to a supplier placing/accepting an order. This email is intended for the buyer.
	 */
	public function getSupplierCloseEmail($htmlFile, $data) {
		$resultset = Auctions::model()->getAuction($data['auction_ID']);
		
		foreach ($resultset as $row) {
			$data['auction_start'] = $row->auction_start;
			$data['auction_end'] = $row->auction_end;
			$data['delivery_due'] = $row->delivery_due;
			$data['gallon'] = $row->gallon;
			$productID = $row->product_ID;
			$siteID = $row->site_ID;
			$tankID = $row->tank_ID;
		}
		
		$data['product'] = Products::model()->getProductName($productID);
		$data['site'] = Sites::model()->getSiteName($siteID);
		$data['tank'] = Tanks::model()->getTankName($tankID);
		
		$resultset = Organizations::model()->getOrganization(Yii::app()->user->userID);
		
		foreach ($resultset as $row) {
			$data['organization_name'] = $row->organization_name;
			$data['phone_number'] = $row->phone_number;
			$data['email_address'] = $row->email_address;
			$data['address'] = $row->address1 . ', ' . $row->address2;
			$data['contact_name'] = $row->contact_first_name . ' ' . $row->contact_last_name;
		}
		
		$resultset = BidAuctions::model()->getAuction(Yii::app()->user->userID, $data['auction_ID']);
		
		foreach ($resultset as $row) {
			$data['fuel_cost_per_gallon'] = $row->fuel_cost_per_gallon;
		}
		
		$htmlFile = str_replace('[auctionID]', $data['auction_ID'], $htmlFile);
		$htmlFile = str_replace('[supplier]', $data['organization_name'], $htmlFile);
		$htmlFile = str_replace('[site]', $data['site'], $htmlFile);
		$htmlFile = str_replace('[tank]', $data['tank'], $htmlFile);
		$htmlFile = str_replace('[auctionStart]', $data['auction_start'], $htmlFile);
		$htmlFile = str_replace('[auctionEnd]', $data['auction_end'], $htmlFile);
		$htmlFile = str_replace('[deliveryRequest]', $data['delivery_due'], $htmlFile);
		$htmlFile = str_replace('[product]', $data['product'], $htmlFile);
		$htmlFile = str_replace('[amountRequested]', $data['gallon'], $htmlFile);
		$htmlFile = str_replace('[contact]', $data['contact_name'], $htmlFile);
		$htmlFile = str_replace('[phone]', $data['phone_number'], $htmlFile);
		$htmlFile = str_replace('[email]', $data['email_address'], $htmlFile);
		$htmlFile = str_replace('[address]', $data['address'], $htmlFile);
		$htmlFile = str_replace('[fuelCost]', $data['fuel_cost_per_gallon'], $htmlFile);
		
		return $htmlFile;
	}
	
	public function getError() {
		return $error;
	}
}
?>